#include "io_service_pool.h"


io_service_pool::io_service_pool(size_t	pool_size)
	:m_next_io_service(0)
{
	for (size_t i = 0; i < pool_size; ++i)
	{
		io_service_sptr service(new asio::io_service);
		work_sptr work(new asio::io_service::work(*service));
		m_io_services.push_back(service);
		m_work.push_back(work);
	}
}


io_service_pool::~io_service_pool()
{
}

void io_service_pool::start()
{
	for (size_t i = 0; i < m_io_services.size(); ++i)
	{
		boost::shared_ptr<thread> thrd(new boost::thread(boost::bind(&asio::io_service::run, m_io_services[i])));
		m_threads.push_back(thrd);
	}
}

void io_service_pool::join()
{
	for (size_t i = 0; i < m_threads.size(); i++)
	{
		m_threads[i]->join();
	}
}

void io_service_pool::stop()
{
	for (size_t i = 0; i < m_io_services.size(); i++)
	{
		m_io_services[i]->stop();
	}
}

asio::io_service& io_service_pool::get_io_service()
{
	boost::mutex::scoped_lock lock(m_mutex);
	boost::asio::io_service& io_service = *m_io_services[m_next_io_service];
	++m_next_io_service;
	if (m_next_io_service == m_io_services.size())
	{
		m_next_io_service = 0;
	}

	return io_service;
}
